package com.card.storage;

import java.util.List;

import com.card.user.UserBase;
import com.card.user.UserDataComponent;
import com.google.common.collect.Lists;

import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;

public class UserStorage extends UserDataComponent{
	private List<UserItem> itemList = Lists.newArrayList();
	private transient TIntObjectMap<UserItem> itemMap = new TIntObjectHashMap<>();
	
	private boolean isDayReward;
	@Override
	public void LateInit(UserBase context) {
		super.LateInit(context);
		for (UserItem userItem : itemList) {
			itemMap.put(userItem.getItemId(), userItem);
		}
	}
	/**
	 * 添加道具id
	 * @param item
	 */
	public void addItem(Item item) {
		UserItem userItem = itemMap.get(item.getId());
		if(userItem == null) {
			userItem = new UserItem(item.getId(), item.getCount());
			itemList.add(userItem);
			itemMap.put(userItem.getItemId(), userItem);
		}else{
			userItem.setCount(item.getCount()+userItem.getCount());
		}
		SetChanged();
	}
	public void addItem(int id,int count) { 
		addItem(new Item(id, count));
	}
	public void addItem(int id) { 
		addItem(new Item(id, 1));
	}
	public void setItem(int id,int count) { 
		UserItem userItem = itemMap.get(id);
		if(userItem == null) {
			userItem = new UserItem(id, count);
			itemList.add(userItem);
			itemMap.put(userItem.getItemId(), userItem);
		}else{
			userItem.setCount(count);
		}
		SetChanged();
	}
	
	
	public boolean isDayReward() {
		return false;
	}
	public void setDayReward(boolean isDayReward) {
		this.isDayReward = isDayReward;
		SetChanged();
	}
	/**
	 * 检查是否能消耗
	 * @param spend
	 * @return
	 */
	public boolean checkCanSpend(Item item) {
		UserItem userItem = itemMap.get(item.getId());
		return userItem != null && userItem.getCount()>=item.getCount();
	}
	/**
	 * 消耗金币
	 * @param spend
	 */
	public boolean spendItem(Item item) {
		if(checkCanSpend(item)) {
			UserItem userItem = itemMap.get(item.getId());
			if(userItem != null) userItem.setCount(userItem.getCount()-item.getCount());
			SetChanged();
			return true;
		}
		return false;
	}
	
	public int getItemCount(int itemId) {
		UserItem userItem = itemMap.get(itemId);
		if(userItem != null) {
			return userItem.getCount();
		}
		return 0;
	}
}
